package org.jetnuke.modules.jforum;

import org.apache.log4j.Logger;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.Command;
import net.jforum.ControllerUtils;
import net.jforum.JForumContext;
import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.repository.ModulesRepository;
import net.jforum.util.I18n;
import net.jforum.util.MD5;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import freemarker.template.SimpleHash;

public class Utils {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Utils.class);

	private Utils() {
	}

	private static String encoding = "UTF-8";

	public static String jforumService(ActionServletRequest req,
			HttpServletResponse response) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("jforumService(ActionServletRequest, HttpServletResponse) - start"); //$NON-NLS-1$
		}

		// JForum.DataHolder
		// dataHolder=(JForum.DataHolder)JForumBaseServlet.localData.get();

		// dataHolder.getContext();

		SimpleHash context = JForumExecutionContext.getTemplateContext();

		ControllerUtils utils = new ControllerUtils();
		utils.refreshSession();
		//		
		// context.put("logged", SessionFacade.isLogged());
		//		
		// // Process security data
		// SecurityRepository.load(SessionFacade.getUserSession().getUserId());

		req.setJForumContext(new JForumContext(req.getContextPath(),
				SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION), req,
				response, SessionFacade.getUserSession().isBot()));

		utils.prepareTemplateContext(context, req.getJForumContext());

		ActionServletRequest request = JForumExecutionContext.getRequest();
		String module = request.getParameter("module"); // request.getModule();
		String action = request.getParameter("action");// JForum.getRequest().getAction();

		if (module == null) {
			module = "forums";
		}
		// else if(module.equals("priv_msg")){
		// module="pm";
		// if(action==null){
		// action="inbox";
		// request.addParameter("action",action);
		// }
		// }
		// else if (module.equals("members_list")){
		// module="user";
		// if(action==null){
		// action="list";
		// request.addParameter("action",action);
		// }
		// }
		if (action == null) {
			action = "list";
			request.addParameter("action", action);
		}

		// Gets the module class name
		String moduleClass = module != null ? ModulesRepository
				.getModuleClass(module) : null;

		context.put("moduleName", module);
		context.put("action", request.getAction());
		context.put("language", I18n.getUserLanguage());
		context.put("imagesI18n", I18n.getUserLanguage());
		context.put("securityHash", MD5.crypt(request.getSession().getId()));
		context.put("session", SessionFacade.getUserSession());
		context.put("request", req);
		context.put("response", response);

		StringWriter out = new StringWriter();

		// Connection conn = null;
		// boolean autoCommitStatus = true;
		// boolean useTransactions =
		// SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS);
		// if (!isDatabaseUp) {
		// ForumStartup.startDatabase();
		// }

		// if (isDatabaseUp) {

		// conn=JForumExecutionContext.getConnection();

		// }
		JForumExecutionContext.setContentType("text/html");
		if (moduleClass != null) {

			Command c = (Command) Class.forName(moduleClass).newInstance();
			freemarker.template.Template template = c.process(request,
					response, context);

			if (JForumExecutionContext.getRedirectTo() == null) {
				String contentType = JForumExecutionContext.getContentType();
				if (contentType == null) {
					contentType = "text/html; charset=" + encoding;
				}

				response.setContentType(contentType);
				template.process(JForumExecutionContext.getTemplateContext(),
						out);
				out.flush();
			}
		}

		String redirectTo = JForumExecutionContext.getRedirectTo();

		if (redirectTo != null) {
			JForumExecutionContext.getResponse().sendRedirect(redirectTo);
			// JForum.localData.set(null);

			if (logger.isDebugEnabled()) {
				logger
						.debug("jforumService(ActionServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
			}
			return null;
		}

		// JForum.localData.set(null);
		String returnString = out.toString();
		if (logger.isDebugEnabled()) {
			logger
					.debug("jforumService(ActionServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
		}
		return returnString;
	}

}
